const express = require('express')
const multiparty = require('multiparty')
const fs = require('fs')
const path = require('path')
const { Buffer } = require('buffer')
var chunkuploadApi = express.Router()// 创建一个路由实例
// file path
const STATIC_FILES = path.join(__dirname, './files')
// Temporary path to upload files
const STATIC_TEMPORARY = path.join(__dirname, './temporary')

// console.log('zdy------>' + 'STATIC_FILES is ' + STATIC_FILES)
// console.log('zdy------>' + 'STATIC_TEMPORARY is ' + STATIC_TEMPORARY)
// if (!fs.existsSync(STATIC_FILES)) {
//     fs.mkdirSync(STATIC_FILES);
//     console.log('zdy------>' + '文件夹生成成功 is ' + STATIC_FILES)
// }
// if (!fs.existsSync(STATIC_TEMPORARY)) {
//     fs.mkdirSync(STATIC_TEMPORARY);
//     console.log('zdy------>' + '文件夹生成成功 is ' + STATIC_TEMPORARY)
// }



// Static file hosting
// server.use(express.static(path.join(__dirname, '/uploads')))
// Interface for uploading slices
chunkuploadApi.post('/upload', (req, res) => {
    const form = new multiparty.Form();
    form.parse(req, function (err, fields, files) {
        console.log('zdy------>' + 'fields is ' + JSON.stringify(fields))
        console.log('zdy------>' + 'files is ' + JSON.stringify(files))
        let filename = fields.filename[0]
        console.log('zdy------>' + 'post enter upload: filename is ' + filename)
        let chunk = files.chunk[0]
        let originalFilename = chunk.originalFilename
        console.log('zdy------>' + 'post enter upload: chunk.originalFilename is ' + originalFilename)
        let chunkname = originalFilename.substring(0, originalFilename.indexOf("."))
        let dir = `${STATIC_TEMPORARY}/${filename}`
        try {
            if (!fs.existsSync(dir)) fs.mkdirSync(dir)
            const buffer = fs.readFileSync(chunk.path)
            // const ws = fs.createWriteStream(`${dir}/${hash}`)
            const ws = fs.createWriteStream(`${dir}/${chunkname}`)
            ws.write(buffer)
            ws.close()
            // res.send(`${filename}-${hash} Section uploaded successfully`)
            res.send(`${chunkname} Section uploaded successfully`)
        } catch (error) {
            console.error(error)
            res.status(500).send(`${chunkname} Section uploading failed`)
        }
    })
})

//Merged slice interface
chunkuploadApi.get('/merge', async (req, res) => {
    const { filename } = req.query
    let name = filename.substring(0, filename.indexOf("."))
    console.log('zdy------>' + 'merge enter name is ' + name)
    try {
        let len = 0
        const bufferList = fs.readdirSync(`${STATIC_TEMPORARY}/${filename}`).map((hash, index) => {
            const buffer = fs.readFileSync(`${STATIC_TEMPORARY}/${filename}/${name + index}`)
            len += buffer.length
            return buffer
        });
        //Merge files
        const buffer = Buffer.concat(bufferList, len);
        const ws = fs.createWriteStream(`${STATIC_FILES}/${filename}`)
        ws.write(buffer);
        ws.close();
        res.send(`Section merge completed`);
    } catch (error) {
        console.error(error);
    }
})

// chunkuploadApi.listen(8080, _ => {
//     console.log('zdy------>' + 'Files Server listening on port 8080')
// })

module.exports = chunkuploadApi